<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? '新增' : '编辑'"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      class="formWrapper"
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      label-width="120px"
    >
      <el-form-item v-if="parentName" label="上级分类">
        <el-input v-model="parentName" disabled></el-input>
      </el-form-item>
      <el-form-item prop="name" label="产品分类名称">
        <el-input v-model="dataForm.name" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="产品图片">
        <el-upload
          class="upload-demo"
          ref="upload"
          action=""
          :auto-upload="false"
          :file-list="fileList"
          :limit="1"
          :on-change="handleUpload"
          :on-remove="handleRemove"
          list-type="picture-card"
          name="pic"
          :class="{ hide: hideUpload }"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <div class="picDes">
          <div>上传说明：</div>
          <div>1.格式限制：JNG、PNG、JPEG</div>
          <div>2.大小限制：每张图片大小为10M以内，尺寸建议200*200</div>
          <!-- <div>3.最多可以上传10张图片，第一张将默认为主图，用于封面展示</div> -->
        </div>
      </el-form-item>
      <el-form-item prop="sort" label="排序">
        <el-input placeholder="请输入" type="number" v-model="dataForm.sort">
        </el-input>
        <div class="tipLabel">数值越大，排序越靠前</div>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t('confirm')
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import { selfUpload, getClassifyDetail, addClassify } from '@/api'
import { jsonObjToFormObj } from '@/utils'
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: '',
        name: '',
        pic: '',
        sort: 1,
      },
      hideUpload: false,
      limitCount: 1,
      fileList: [],
      parentName: '',
    }
  },
  computed: {
    dataRule() {
      return {
        name: [
          {
            required: true,
            message: '必填项不能为空',
            trigger: 'blur',
          },
        ],
        sort: [
          {
            required: true,
            message: '必填项不能为空',
            trigger: 'blur',
          },
        ],
      }
    },
  },
  created() {
    console.log(this.dataForm.id)
  },
  methods: {
    init() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取信息
    async getInfo() {
      const data = {
        id: this.dataForm.id,
      }
      const res = await getClassifyDetail(data)
      this.dataForm = {
        ...this.dataForm,
        ...res.data,
      }
      const pic = res?.data?.pic
      if (pic) {
        this.fileList = [{ name: '', url: pic || '' }]
        this.hideUpload = true
      }
      console.log(this.dataForm)
      // this.$http
      //   .get(`/sys/dict/type/${this.dataForm.id}`)
      //   .then(({ data: res }) => {
      //     if (res.code !== 0) {
      //       return this.$message.error(res.msg);
      //     }
      //     this.dataForm = {
      //       ...this.dataForm,
      //       ...res.data,
      //     };
      //   })
      //   .catch(() => {});
    },
    async handleUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
        this.$refs.upload.clearFiles()
        return
      }
      const params = {}
      params.file = file.raw
      const formData = jsonObjToFormObj(params)
      const res = await selfUpload(formData)
      if (res?.status === 1) {
        this.$message({
          message: res.msg,
          type: 'success',
          duration: '1000',
        })
        this.dataForm.pic = res?.url || ''
        this.hideUpload = true
      }
    },
    handleRemove() {
      this.dataForm.pic = ''
      this.hideUpload = false
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function() {
        this.$refs['dataForm'].validate(async (valid) => {
          if (!valid) {
            return false
          }
          const params = { ...this.dataForm }
          params.id = this.dataForm.id ? this.dataForm.id : 0
          const res = await addClassify(params)
          if (res?.status === 1) {
            this.$refs.upload.clearFiles()
            this.$refs['dataForm'].resetFields()
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              },
            })
          }
          this.hideUpload = false
          this.parentName = ''
          // this.$http[!this.dataForm.id ? "post" : "put"](
          //   "/sys/dict/type",
          //   this.dataForm
          // )
          //   .then(({ data: res }) => {
          //     if (res.code !== 0) {
          //       return this.$message.error(res.msg);
          //     }
          //     this.$message({
          //       message: this.$t("prompt.success"),
          //       type: "success",
          //       duration: 500,
          //       onClose: () => {
          //         this.visible = false;
          //         this.$emit("refreshDataList");
          //       },
          //     });
          //   })
          //   .catch(() => {});
        })
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
}
</script>
<style lang="scss" scoped>
.formWrapper {
  .picDes {
    margin-top: 12px;
    font-size: 12px;
    color: #999;
    line-height: 18px;
  }

  .hide {
    ::v-deep .el-upload--picture-card {
      display: none;
    }
  }
}
</style>
